package com.liuchuanzheng.lcz_wanandroid.module.mine.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus
import com.liuchuanzheng.lcz_wanandroid.base.BaseFragment
import com.liuchuanzheng.lcz_wanandroid.databinding.FragmentHomeBinding
import com.liuchuanzheng.lcz_wanandroid.databinding.FragmentMineBinding
import com.liuchuanzheng.lcz_wanandroid.module.common.bus.LoginStatusEvent
import com.liuchuanzheng.lcz_wanandroid.module.mine.activity.SettingsActivity
import com.liuchuanzheng.lcz_wanandroid.module.user.UserManager
import com.liuchuanzheng.lcz_wanandroid.module.user.activity.LoginActivity
import com.liuchuanzheng.lcz_wanandroid.util.log.LogUtil

/**
 * @author 刘传政
 * @date 2021/9/14 0014 17:24
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
class MineFragment:BaseFragment() {
    lateinit var mViewBinding: FragmentMineBinding
    /**
     * 当页面可见的时候，才加载当前页面。 没有打开的页面，就不会预加载。
     *
     *
     * 说白了，懒加载就是可见的时候才去请求数据。
     * 只回调一次
     */
    override fun onLazyLoad() {

    }

    /**
     * 因为系统自带的设置view方法有很多种,id,view都可以.所以这里不像
     * 大家都用id的封装方式,那是限制了自己
     * @param inflater
     * @param container
     */
    override fun creatView(inflater: LayoutInflater?, container: ViewGroup?): View {
        mViewBinding = FragmentMineBinding.inflate(inflater!!, container, false)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewBinding.clHeader.setOnClickListener {
            if (!UserManager.isLogin()) {
                LoginActivity.start(requireActivity())
            }
        }
        updateUi()
        LiveEventBus
            .get(LoginStatusEvent::class.java)
            .observe(this, Observer {
                updateUi()

            })
        mViewBinding.llSetting.setOnClickListener {
            SettingsActivity.start(requireContext())
        }
    }
    private fun updateUi() {
        val isLogin = UserManager.isLogin()
        val userInfo = UserManager.getUserInfo()
        mViewBinding.tvLoginRegister.isGone = isLogin
        mViewBinding.tvNickName.isVisible = isLogin
        mViewBinding.tvId.isVisible = isLogin
        if (isLogin && userInfo != null) {
            mViewBinding.tvNickName.text = userInfo.nickname
            mViewBinding.tvId.text = "ID: ${userInfo.id}"
        }
    }
}